package com.elysium.template;

import com.elysium.properties.CosSettingProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingResponse;
import org.springframework.util.Assert;

import java.io.InputStream;

public class CosTemplate {

    private CosSettingProperties cosSettingProperties;

    private COSClient cosClient;

    public CosTemplate(CosSettingProperties cosSettingProperties, COSClient cosClient) {
        this.cosSettingProperties = cosSettingProperties;
        this.cosClient = cosClient;
    }

    /**
     * 图片上传
     * @param inputStream
     * @param floder
     * @param imageName
     * @return
     */
    public String uploadFile(InputStream inputStream, String floder, String imageName){
        String bucketName = cosSettingProperties.getBucketName();

        String key = floder + "/" + imageName;

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, new ObjectMetadata());
        PutObjectResult putObjectResult = this.cosClient.putObject(putObjectRequest);

        // https://java0403-1318041359.cos.ap-chengdu.myqcloud.com/fccar%2F1722927132943.jpg
        // https://%s.cos.%s.myqcloud.com/%s/%s  桶名  地域  文件夹名称  文件名称
        String eTag = putObjectResult.getETag();
        if ("null".equals(eTag) || null == eTag){
            throw new RuntimeException("上传图片失败！");
        }

        Boolean aBoolean = this.imageAuditing(bucketName, key);
        Assert.isTrue(aBoolean, "图片审核失败！");

        String filePath = String.format(cosSettingProperties.getImagePathTemplate(), bucketName, cosSettingProperties.getRegion(), floder, imageName);
        return filePath;
    }

    /**
     * 图片审核
     * @param bucketName
     * @param objectKey
     * @return
     */
    public Boolean imageAuditing(String bucketName, String objectKey){
        //1.创建任务请求对象
        ImageAuditingRequest request = new ImageAuditingRequest();
        //2.添加请求参数 参数详情请见api接口文档
        //2.1设置请求bucket
        request.setBucketName(bucketName);
        //2.2设置审核类型
        request.setDetectType(cosSettingProperties.getDetectType());
        //2.3设置bucket中的图片位置
        request.setObjectKey(objectKey);
        //3.调用接口,获取任务响应对象
        ImageAuditingResponse response = this.cosClient.imageAuditing(request);

        return "0".equals(response.getResult());
    }


}
